'''
Created on Dec 6, 2009

@author: bodnaria
'''
import os
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import appengine_utilities.sessions
from util import AuthorizedPage
import hashlib
from model.User import getUserByUsername
from error.UserError import UserError as UserError


class EditProfilePage(AuthorizedPage):
    def getIfAuthorized(self):
        messages = {"badfields" : "Please fill out all fields properly.",
                    "unknown":"An unknown error occured. Please try again.", }        
        
        user = self.authorizedUser
        
        self.outputHeader()

        error = self.request.get("error")
        if not error in messages.keys():
            message = ""
        else:
            message = messages[error]

        template_values = {
            "username" : user.username,
            "name" : user.name,
            "ismale" : user.gender == "Male",
            "age" : user.age,
            "location" : user.city,
            "website" : user.link,
            "description" : user.desc,
            "error" : message,
            "targetpage" : "/create_profile",
        }

        templatePath = os.path.join(os.path.dirname(__file__), 'edit_profile.html')
        self.response.out.write(template.render(templatePath, template_values)) 
    
    def postIfAuthorized(self):
        name = cgi.escape(self.request.get("name"))
        gender = cgi.escape(self.request.get("gender"))
        age = int(cgi.escape(self.request.get("age")))
        city = cgi.escape(self.request.get("location"))
        desc = cgi.escape(self.request.get("desc"))
        link = cgi.escape(self.request.get("website"))
        
        try:
            user = self.authorizedUser
            
            user.updateName(name)
            user.updateAge(age)
            user.updateGender(gender)
            user.updateCity(city)
            user.updateDesc(desc)
            user.updateLink(link)
            
                           
        except ValueError:
            self.redirect('edit_profile/?error=badfields')
            return 
        
        self.redirect('/profile?user='+user.username)
        
        
